package controller

import (
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
	"gomicro/microGrpc/grpcMessage"
	"context"
	// "github.com/micro/go-micro/client"
	"fmt"
	"github.com/micro/go-grpc"
)

var (
	cli grpcMessage.StudentService
)

func init(){
	grpcServer := grpc.NewService()
	cli = grpcMessage.NewStudentService("student_micro_grpc_service", grpcServer.Client())
}


type StudentMicroController struct{
    Ctx  iris.Context
}

func (c *StudentMicroController) PostMicroinsert() mvc.Result {
	id := c.Ctx.FormValue("id")
	name := c.Ctx.FormValue("name")
	birth := c.Ctx.FormValue("birth")
	sex := c.Ctx.FormValue("sex")
	
	var as = grpcMessage.AddUpStudent{Id: id,
							Name:name,
							Birth:birth,
							Sex:sex,
						}

	res, err := cli.InsertStudent(context.TODO(), &as)
	if err != nil {
		fmt.Println(err)
		return mvc.Response{
			Object : res,
		}
	}
	
	return mvc.Response{
        Object : res,
    }
}

func (c *StudentMicroController) PostMicrodelete() mvc.Result {
	name := c.Ctx.FormValue("name")

	var ds = grpcMessage.DelStudent{
		Name:name,
	}

	res, err := cli.DeleteStudent(context.TODO(), &ds)
	if err != nil {
		fmt.Println(err)
		return mvc.Response{
			Object : res,
		} 
	}

	return mvc.Response{
		Object : res,
	}
}

func (c *StudentMicroController) PostMicroupdate() mvc.Result {
	id := c.Ctx.FormValue("id")
	name := c.Ctx.FormValue("name")
	birth := c.Ctx.FormValue("birth")
	sex := c.Ctx.FormValue("sex")

	var as = grpcMessage.AddUpStudent{Id: id,
		Name:name,
		Birth:birth,
		Sex:sex,
	}

	res, err := cli.UpdateStudent(context.TODO(), &as)
	if err != nil {
		fmt.Println(err)
		return mvc.Response{
			Object : res,
		} 
	}

	return mvc.Response{
		Object : res,
	}
}

func (c *StudentMicroController) PostMicroquery() mvc.Result {

	var l = grpcMessage.List{}

	res, err := cli.QueryStudent(context.TODO(), &l)
	if err != nil {
		fmt.Println(err)
		return mvc.Response{
			Object : res,
		} 
	}

	return mvc.Response{
		Object : res,
	}
}


